<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.device" placeholder="通道号/设备id" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      class="channel-table"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
      @cell-mouse-leave="handleMouseOut"
    >
      <el-table-column align="center" label="序号" min-width="5%">
        <template slot-scope="scope">
          {{ (listQuery.page-1)*10 + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="名称" align="left" min-width="20%">
        <template slot-scope="scope">
          <span v-if="!scope.row.edit">{{ scope.row.device_name }}</span>
          <span v-if="scope.row.edit" class="cell-edit-input">
            <el-input v-model="scope.row.device_name" placeholder="请输入设备名称" />
          </span>
          <span v-if="!scope.row.edit" style="margin-left:10px;" class="cell-icon" @click="handleEdit(scope.$index,scope.row)">
            <i class="el-icon-edit" />
          </span>
          <span v-if="scope.row.edit" style="margin-left:10px;" class="cell-icon" @click="handleSave(scope.$index,scope.row)">
            <i class="el-icon-document" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" min-width="12%">
        <template slot-scope="scope">
          <span>{{ scope.row.protocol }}</span>
        </template>
      </el-table-column>
      <el-table-column label="国标设备id" align="center" min-width="18%">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通道" align="center" min-width="4%">
        <template slot-scope="scope">
          <span>{{ scope.row.sumnum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="媒体服务器" align="center" min-width="7%">
        <template slot-scope="scope">
          <span>{{ scope.row.server_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" min-width="5%">
        <template slot-scope="scope">
          <div v-if="scope.row.online===1">
            <el-tag type="success">在线</el-tag>
          </div>
          <div v-else>
            <el-tag type="danger">离线</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="32%" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" class="el-icon-arrow-right" size="mini" @click="channels(scope.row.deviceid)">查看通道</el-button>
          <el-button class="el-icon-refresh" size="mini" @click="catalog(scope.row.deviceid)">更新通道</el-button>
          <el-button size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" class="el-icon-delete" size="mini" @click="del(scope.row.deviceid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: center;margin-top: 30px;">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page.sync="listQuery.page"
        :page-size="listQuery.pagesize"
        @current-change="current_change"
      />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="设备类型" prop="protocol">
          <el-select v-model="temp.protocol" placeholder="设备类型">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="device_name">
          <el-input v-model="temp.device_name" />
        </el-form-item>
        <el-form-item label="国标设备id" prop="deviceid">
          <el-input v-model="temp.deviceid" readonly="true" />
        </el-form-item>
        <el-form-item label="通道数量" prop="sumnum">
          <el-input v-model="temp.sumnum" readonly="true" />
        </el-form-item>
        <el-form-item label="服务器ID" prop="type">
          <el-select v-model="temp.server_id" class="filter-item" placeholder="Please select">
            <el-option v-for="item in servers" :key="item.id" :label="item.server_id" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { list, catalog, deldevice, updatename, update } from '@/api/device'
import * as mediaServer from '@/api/mediaServer'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      options: [{
        value: 'GB28181',
        label: 'GB28181'
      }, {
        value: 'RTSP拉流',
        label: 'RTSP拉流'
      }],
      listQuery: {
        page: 1,
        pagesize: 20,
        device: undefined
      },
      list: null,
      // 记录数量
      total: 0,
      listLoading: true,
      textMap: {
        update: '修改设备信息',
        create: '新增设备信息'
      },
      servers: [

      ],
      temp: {
        id: undefined,
        server_id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        server_id: [{ required: true, message: '请选择媒体服务器', trigger: 'change' }]
      }
    }
  },
  created() {
    if (sessionStorage.getItem('gbDevicePage')) {
      this.listQuery.page = parseInt(sessionStorage.getItem('gbDevicePage'))
    }
    this.getMediaServerList()
    this.fetchData()
  },
  methods: {
    getMediaServerList() {
      mediaServer.list({}).then((ret) => {
        this.servers = Object.assign([], ret.data.items)
      })
    },
    fetchData() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data.items
        if (this.list) {
          this.list.forEach((item) => {
            item.edit = false
          })
        }
        this.listLoading = false
        this.total = response.data.total
      })
    },
    current_change: function(page) {
      this.listQuery.page = page
      this.fetchData()
    },
    // 进入子通道
    channels(parentId) {
      sessionStorage.setItem('gbDevicePage', this.listQuery.page)
      this.$router.push({ path: '/devices/channels', query: { parentId: parentId }})
    },
    // 刷新目录
    catalog(id) {
      this.listLoading = true
      catalog({ parentId: id }).then(response => {
        console.log('catalog response', response)
        this.listLoading = false
      })
    },

    del(parentId) {
      this.$confirm('确认删除此通道？').then(_ => {
        this.listLoading = true
        deldevice({ parentId: parentId }).then(() => {
          this.listLoading = false
          this.fetchData()
        })
      }).catch(_ => {

      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          this.listLoading = true
          update(tempData).then((ret) => {
            if (ret.code === 20000) {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: ret.message,
                type: 'success',
                duration: 2000
              })
              this.listLoading = false
              this.fetchData()
            }
          }).catch((err) => {
            console.error(err)
          })
        }
      })
    },
    handleClose(done) {
      done()
    },
    handleEdit(index) {
      this.list[index].edit = true
    },
    handleSave(index, row) {
      updatename({ deviceid: row.deviceid, device_name: row.device_name }).then(() => {
        console.log('保存')
        this.list[index].edit = false
        this.$forceUpdate()
      })
    },
    handleMouseEnter(row, column, cell) {
      if (column.label !== '名称') return
      if (cell.children[0].children[1]) {
        cell.children[0].children[1].style.color = 'black'
      }
    },
    handleMouseOut(row, column, cell) {
      if (column.label !== '名称') return
      if (cell.children[0].children[1]) {
        cell.children[0].children[1].style.color = '#ffffff'
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      sessionStorage.removeItem('gbDevicePage')
      this.fetchData()
    }
  }
}
</script>

<style>
	.cell-icon{
		cursor:pointer;
		color:#fff;
	}
</style>
